/**
 * bootstrap 4 Loading 组件
 * 
 * $.loading({
 *     var loading = $.loading();
 *     
 *     loading.setPercent(50);
    
 *     setTimeout(function() {
 *         loading.unloading(); // 也可以直接 $.unloading();
 *     }, 3000);
 * });
 */
;
(function ($) {
    'use strict';

    var loading = function (opts) {

        this.opts = opts = $.extend({}, {
            id: 'loading', // 指定ID
            title: '加载中...', // 文本描述
            percent: 100, // 进度百分比
        }, opts);

        if ($(`#${opts.id}`).length) {
            return false;
        }

        var toast = `
            <div class="toast" id="${opts.id}" style="position: fixed; left: 45%; top: 30%; min-width: 200px; z-index: 99999;">
                <div class="toast-header">
                    <div class="toast-icon bg-primary mr-2" style="width: 1rem; height: 1rem; border-radius: 20%;"></div>
                    <strong class="mr-auto">${opts.title}</strong>
                    <small class="text-muted" id="${opts.id}_percent_tips"></small>
                </div>
                <div class="toast-body">
                    <div class="progress">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" id="${opts.id}_progress_bar"></div>
                    </div>
                </div>
            </div>`;

        this.setPercent = function (percent) {

            if (percent > 100) {
                percent = 100;
            }

            if (percent < 0) {
                percent = 0;
            }

            if (percent != 100) {
                $(`#${opts.id}_percent_tips`).text(percent + '%');
            } else {
                $(`#${opts.id}_percent_tips`).text('');
            }

            $(`#${opts.id}_progress_bar`).css('width', percent + '%');

        };

        this.unloading = function () {
            $(`#${opts.id}`).toast('hide');
            $(`#${opts.id}`).remove();
        };

        $('body').append(toast);

        this.setPercent(opts.percent);

        $(`#${opts.id}`).css('opacity', 100);

    };

    $.extend({
        loading: function (opts) {
            let loading1 = new loading(opts);
            if (!window.loadings) {
                window.loadings = [];
            }
            window.loadings.push(loading1);
            return loading1;
        },
        unloading: function() {
            window.loadings.forEach((loading1) => {
                loading1.unloading();
            });
            window.loadings = [];
        },
    }); // $.loading() 方式

})(window.jQuery);